<template>
  <chat-layout
    class="page"
    ref="chatLayout"
    :end="end"
    @upper-loading="loadMoreLog"
  >
    <chat-message-item
      v-for="item in chatLogs"
      :self="item.self"
      :head="item.head"
      :type="item.type"
      :data="item.data"
    >
    </chat-message-item>
    <template #bottom>
      <chat-input-box
        @send-text="sendText"
        @send-audio="sendAudio"
        @send-video="sendVideo"
        @send-image="sendImage"
        @send-location="sendLocation"
        @voip-audio="startAudioVoip"
        @voip-video="startVideoVoip"
      ></chat-input-box>
    </template>
  </chat-layout>
</template>

<script>
  import _ from 'lodash'
  export default {
    onLoad (params) {
      this.receiver = params.receiver
    },
    data () {
      return {
        end: false,
        receiver: '',
        chatLogs: [],
        loadCount: 1,
      }
    },
    watch: {
      chatLogs: {
        deep: true,
        async handler () {
          // await this.$nextTick()
          // this.$refs.chatLayout.scrollToBottom()
        }
      }
    },
    beforeDestroy () {
      this.$imUtils.stopAudio()
    },
    async mounted () {
      await this.getLogs()
      await this.$nextTick()
      this.$refs.chatLayout.scrollToBottom()
      uni.setNavigationBarTitle({
        title: this.receiver
      })
      // 监听新的消息
			this.$txim.$on('onRecvC2CTextMessage', this.onRecvMessageHanlder)
			this.$txim.$on('onRecvC2CCustomMessage', this.onRecvMessageHanlder)
			this.$txim.$on('onRecvGroupTextMessage', this.onRecvMessageHanlder)
			this.$txim.$on('onRecvGroupCustomMessage', this.onRecvMessageHanlder)
			this.$txim.$on('onRecvNewMessage', this.onRecvMessageHanlder)
    },
    onNavigationBarButtonTap({ index }) {
      if (index === 0) {
				uni.navigateTo({
					url: './profile'
				})
      }
    },
    methods: {
      // 腾讯系历史记录转成组件格式
      async HistoryMessageToChatLog (msgLogs, unshift) {
        for (let item of msgLogs) {
          let msgType = [
            null,
            this.$imUtils.MSG_TEXT,
            null,
            this.$imUtils.MSG_IMAGE,
            this.$imUtils.MSG_AUDIO,
            this.$imUtils.MSG_VIDEO,
            null,
            this.$imUtils.MSG_LOCATION,
            null,
          ][item.elemType]
          let dataJson = {
            id: item.msgID,
            head: '../static/icon_u_head.jpg',
            self: item.isSelf,
            type: msgType,
            data: null
          }
          switch (msgType) {
            case this.$imUtils.MSG_TEXT:
              dataJson.data = this.$imUtils.buildMessageItem(msgType, item.elem.text, item)
              break
            case this.$imUtils.MSG_LOCATION:
              dataJson.data = this.$imUtils.buildMessageItem(msgType, item, item.elem.latitude, item.elem.longitude, item.elem.desc, item)
              break
            case this.$imUtils.MSG_IMAGE:
              dataJson.data = this.$imUtils.buildMessageItem(msgType, item.elem.imageList[0].url, item)
              break
            case this.$imUtils.MSG_AUDIO:
              dataJson.data = this.$imUtils.buildMessageItem(msgType, '', item.elem.duration * 1000, item)
              break
            case this.$imUtils.MSG_VIDEO:
              dataJson.data = this.$imUtils.buildMessageItem(msgType, item, item)
              break
            default:
              console.log(item)
          }
          if (msgType) {
            this.chatLogs[unshift ? 'unshift' : 'push'](dataJson)
          }
        }
      },
      // 获取消息
      async onRecvMessageHanlder ({ data }) {
        console.log(data)
        let V2TIMMessageManager = this.$txim.getMessageManager()
        let senderId = data.sender.userID || data.sender
        if (senderId == this.receiver) {
          this.HistoryMessageToChatLog([data])
          this.$txim.markC2CMessageAsRead(senderId)
        }
      },
      // 获取历史记录
      async getLogs () {
        let lastMsgId = null
        if (this.chatLogs[0]) {
          lastMsgId = this.chatLogs[0].data.data.msgID || this.chatLogs[0].data.payload.msgID
        }
        let { data } = await this.$txim.getC2CHistoryMessageList(this.receiver, 20, lastMsgId)
        if (data.length === 0) {
          this.end = true
          return
        }
        data = data.filter(item => item.status < 3)
        await this.HistoryMessageToChatLog(data, 'unshift')
        if (data.length < 20) {
          // this.getLogs()
        }
      },
      async loadMoreLog (next) {
        console.log('loadMoreLog')
        await this.getLogs()
        await this.$nextTick()
        next(false)
      },
      // 发送文字
      sendText: _.debounce(async function (text) {
        let V2TIMMessageManager = this.$txim.getMessageManager()
        let v2TIMMessage = V2TIMMessageManager.createTextMessage(text)
        try {
          let ret = await V2TIMMessageManager.sendMessage(v2TIMMessage, this.receiver)
          console.log(ret)
          this.HistoryMessageToChatLog([ret.data])
        } catch (e) {
          this.$utils.toast('发送失败')
        }
        await this.$nextTick()
        this.$refs.chatLayout.scrollToBottom()
      }, 500, { leading: true, trailing: false }),
      // 发送语音
      async sendAudio ({ filePath, timeLen }) {
        let V2TIMMessageManager = this.$txim.getMessageManager()
        let v2TIMMessage = V2TIMMessageManager.createSoundMessage(filePath, (timeLen / 1000).toFixed(0))
        try {
          let ret = await V2TIMMessageManager.sendMessage(v2TIMMessage, this.receiver)
          this.HistoryMessageToChatLog([ret.data])
        } catch (e) {
          this.$utils.toast('发送失败')
        }
        await this.$nextTick()
        this.$refs.chatLayout.scrollToBottom()
      },
      // 发送图片
      async sendImage({ filePaths }) {
        uni.showLoading({ title: '发送中' })
        let V2TIMMessageManager = this.$txim.getMessageManager()
        for (let item of filePaths) {
          let v2TIMMessage = V2TIMMessageManager.createImageMessage(item)
          try {
            let ret = await V2TIMMessageManager.sendMessage(v2TIMMessage, this.receiver)
            this.HistoryMessageToChatLog([ret.data])
          } catch (e) {
            this.$utils.toast('发送失败')
          }
        }
        await this.$nextTick()
        this.$refs.chatLayout.scrollToBottom()
        uni.hideLoading()
      },
      // 发送视频
      async sendVideo({ filePath, type, timeLen, snapshotPath }) {
        uni.showLoading({ title: '压缩中' })
        let V2TIMMessageManager = this.$txim.getMessageManager()
        let v2TIMMessage = V2TIMMessageManager.createVideoMessage(filePath, type, ((timeLen || 1000) / 1000).toFixed(0), snapshotPath)
        try {
          let ret = await V2TIMMessageManager.sendMessage(v2TIMMessage, this.receiver)
          this.HistoryMessageToChatLog([ret.data])
        } catch (e) {
          console.log(e)
          this.$utils.toast('发送失败')
        }
        await this.$nextTick()
        this.$refs.chatLayout.scrollToBottom()
        uni.hideLoading()
      },
      // 发送定位
      async sendLocation ({ longitude, latitude, address }) {
        let V2TIMMessageManager = this.$txim.getMessageManager()
        let v2TIMMessage = V2TIMMessageManager.createLocationMessage(address, longitude, latitude)
        try {
          let ret = await V2TIMMessageManager.sendMessage(v2TIMMessage, this.receiver)
          this.HistoryMessageToChatLog([ret.data])
        } catch (e) {
          this.$utils.toast('发送失败')
        }
        await this.$nextTick()
        this.$refs.chatLayout.scrollToBottom()
      },
      // TRTC Calling 请求语音通话
      startAudioVoip () {
        uni.navigateTo({
          url: `../pages/inline/calling?sender=true&receivers=[${this.receiver}]&type=audio`
        })
      },
      // TRTC Calling 请求视频通话
      startVideoVoip () {
        uni.navigateTo({
          url: `../pages/inline/calling?sender=true&receivers=[${this.receiver}]&type=video`
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page {
    position: fixed;
    width: 100%;
    height: 100%;
  }
</style>
